from info.models import User, News, Category
from . import admin_bp
from flask import render_template, request, jsonify, current_app
from flask import session, redirect, url_for
from flask import g
from info.utils.common import login_user_data
import time
from datetime import datetime
from datetime import timedelta
from info import constants, db
from info.utils.response_code import RET
from info.utils.image_store import qiniu_image_store


@admin_bp.route("/index")
@login_user_data
def admin_index():
    """管理员登录主页"""
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("admin/index.html", data=data)


@admin_bp.route("/login", methods=["POST", "GET"])
@login_user_data
def admin_login():
    """管理员登录页面"""
    if request.method == "GET":
        # 从session中获取管理员信息
        user = g.user
        #
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", None)
        if user_id and is_admin:
            return render_template("admin/index.html", data={"user_info": user.to_dict() if user else None})
        return render_template("admin/login.html")

    # post请求获取用户提交用户提交的数据进行登录校验
    username = request.form.get("username")
    password = request.form.get("password")

    # 校验参数
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    # 逻辑处理
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="查询管理员失败")

    # 校验密码
    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="密码错误")

    # 使用session记录管理员登录信息
    session["user_id"] = user.id
    session["is_admin"] = user.is_admin
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile

    # TODO:挑转到管理员首页
    return redirect(url_for("admin_bp.admin_index"))


@admin_bp.route('/user_count')
@login_user_data
def user_count():
    """展示用户统计页面"""
    # 查询总人数
    total_count = 0
    try:
        # 10001
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增数
    mon_count = 0
    try:
        # 2018-8-31号
        now = time.localtime()
        # 2018-08-01月初  2018-09-01
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # 使用strptime将字符串转成时间date格式 '%Y-%m-%d'
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        # 用户的创建时间 > 每一个月的第一天 -->每一个月的新增人数
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询日新增数
    day_count = 0
    try:
        # 2018-08-31-0:0
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        # 当前时间 > 2018-08-31-0:0(一天的开始时间)
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询图表信息
    # 获取到当天00:00:00时间
    # 2018-08-31
    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        # 2018-08-31 - 1  =  2018-08-30:0:0
        # 2018-08-31 - 2  =  2018-08-29:0:0
        begin_date = now_date - timedelta(days=i)
        #  now_date - timedelta(days=(i))  + timedelta(days=(1))
        #  begin_date + timedelta(days=(1))
        # 2018-08-30:24:00
        # 2018-08-29:24:00
        end_date = begin_date + timedelta(days=1)
        # 记录这个月的每一天  30 29 ....01
        # strftime将date格式转换成字符串
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        # 记录一个月的每天的用户活跃数
        active_count.append(count)

    # 日期反转
    active_date.reverse()
    # 数据反转
    active_count.reverse()

    data = {"total_count": total_count, "mon_count": mon_count, "day_count": day_count, "active_date": active_date,
            "active_count": active_count}

    return render_template('admin/user_count.html', data=data)


@admin_bp.route("/user_list")
@login_user_data
def user_list():
    """用户列表展示"""
    # 1.获取参数
    p = request.args.get("p", 1)
    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        print("出问题啦")
        current_app.logger.error(e)
        p = 1
    # 3.逻辑处理
    print(p)
    user_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        user_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 新闻对象列表转成字典列表
    user_dict_list = []
    for user in user_list if user_list else []:
        user_dict_list.append(user)

    data = {
        "users": user_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    # 4.返回值处理
    return render_template("admin/user_list.html", data=data)


@admin_bp.route("/news_review")
@login_user_data
def news_review():
    """返回待审核新闻列表"""
    p = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 逻辑处理
    news_list = []
    current_page = 1
    total_page = 1

    # 查询审核未通过&未审核的新闻条件
    filter = [News.status != 0]
    # 有关键字代表需要进行查询
    if keywords:
        filter.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filter) \
            .order_by(News.create_time.desc()) \
            .paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("admin/news_review.html", data=data)


@admin_bp.route("/news_review_detail", methods=["POST", "GET"])
@login_user_data
def news_review_detail():
    """新闻审核详情页面"""
    if request.method == "GET":
        news_id = request.args.get("news_id")

        news = None  # type:News
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        news_dict = news.to_dict() if news else None
        data = {
            "news": news_dict
        }
        return render_template("admin/news_review_detail.html", data=data)

    # post 请求 新闻的审核通过&不通过
    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    print(news_id, action)
    # 2.校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if action not in ["accept", "reject"]:
        return jsonify(error=RET.PARAMERR, errmsg="参数填写错误")
    # 3.逻辑处理
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
    # 新闻存在
    if action == "accept":
        # 审核通过
        news.status = 0
    else:
        reason = request.json.get("reason")
        if reason:
            # 补充拒绝理由
            news.reason = reason
            news.status = -1
        else:
            return jsonify(errno=RET.PARAMERR, errmsg="请填写拒绝理由")
        print(reason)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改新闻状态失败")

    # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="OK")


@admin_bp.route("/news_edit")
@login_user_data
def news_edit():
    """新闻编辑页面展示"""
    # 1.获取参数
    p = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    # 2.校验参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 3.逻辑处理
    news_list = []
    current_page = 1
    total_page = 1

    # 不输入关键字的时候所有新闻都可编辑
    filter = []
    if keywords:
        filter.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(p,
                                                                                         constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                         False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 模型列表转字典列表
    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news)

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    # 4.返回值处理
    return render_template("admin/news_edit.html", data=data)


@admin_bp.route("/news_edit_detail", methods=["POST", "GET"])
def news_edit_detail():
    """新闻编辑修改接口"""
    if request.method == "GET":
        news_id = request.args.get("news_id")

        # 查询新闻
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        news_dict = news.to_dict() if news else None
        # 查询所有分类
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 移除最新分类
        categories.pop(0)

        category_dict_list = []
        for category in categories if categories else []:
            category_dict = category.to_dict()
            category_dict["is_selected"] = False
            if news.category.id == category.id:
                category_dict["is_selected"] = True
            category_dict_list.append(category_dict)

        data = {
            "news": news_dict,
            "categories": category_dict_list
        }

        return render_template("admin/news_edit_detail.html", data=data)

    # post请求新闻修改
    # 1.获取参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.form.get("index_image")
    category_id = request.form.get("category_id")
    # 2.校验参数
    if not all([content, category_id]):
        print(title)
        print(digest)
        print(content)
        print(category_id)
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")
    # 3.逻辑处理
    if index_image:
        # 如果传了图片就上传到七牛云去
        image_data = index_image.read()
        try:
            image_name = qiniu_image_store(image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛云错误")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    # 修改新闻对象
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改新闻对象失败")

    return jsonify(errno=RET.OK, errmsg="新闻修改成功")

    # 4.返回值处理


@admin_bp.route("/add_category", methods=["POST"])
def add_category():
    """分类的添加,修改"""
    # 1.获取参数
    category_id = request.json.get('id')
    category_name = request.json.get("name")

    # 校验参数
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 3.逻辑处理
    # 分类编辑
    if category_id:
        category = None
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询分类异常")
        if not category:
            return jsonify(errno=RET.NODATA, errmsg="分类不存在")

        # 修改分类名称
        category.name = category_name
    else:
        category = Category()
        category.name = category_name
        db.session.add(category)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存分类对象异常")
    return jsonify(errno=RET.OK, errmsg="OK")


@admin_bp.route("/category_type")
def category_type():
    """分类列表展示"""
    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    # 移除最新分类
    categories.pop(0)
    category_dict_list = []
    for category in categories if categories else []:
        category_dict_list.append(category.to_dict())
    data = {
        "categories": category_dict_list
    }
    return render_template("admin/news_type.html", data=data)
